import { GetterTree, ActionTree, MutationTree } from 'vuex';
import { RootState } from '~/store';
import { IUserModel } from '~/models/user.model';

export const state: () => { userInfo: IUserModel; [key: string]: any; } = () => ({
  userInfo: {},
});

export type UserModuleState = ReturnType<typeof state>;

export const getters: GetterTree<UserModuleState, RootState> = {
  userInfo: state => state.userInfo || {},
  loggedIn: state => !!(state.userInfo && state.userInfo._id),
};

export const mutations: MutationTree<UserModuleState> = {
  SET_USER: (state, payload) => {
    state.userInfo = payload;
  },
};

export const actions: ActionTree<UserModuleState, RootState> = {
  login({ commit }, payload: { email: string; password: string }): Promise<any> {
    return new Promise(resolve => {
      this.$axios.post('/user/login', { email: payload.email, password: payload.password }).then(res => {
        if (res) {
          commit('SET_USER', res);
          resolve(res);
        }
      });
    });
  },
  
  logout({ commit }): Promise<void> {
    commit('SET_USER', null);
    return Promise.resolve();
  }
};
